// 扩展中间件
export const extendMiddleware = vue => next => (...params) => {
  const loading = vue.prototype.$loading
  loading.start()
  return next(...params).then(({ data, err }) => {
    loading.done()
    if (err) throw err
    return { data, err }
  })
}
// 缓存中间件
export const cacheMiddleware = vue => next => (...params) => {
  return next(...params).then(({ data, err }) => {
    return { data, err }
  })
}
// 日志中间件
export const logMiddleware = vue => next => (...params) => {
  const { name: fname } = next
  const start = Date.now()
  return next(...params).then(data => {
    const img = data.err
      ? 'https://tu.jiuwa.net/pic/20170910/1505053332939917.jpg'
      : 'http://pic.9ht.com/up/2018-2/15181644163000303.jpg'
    console.group('API接口调用')
    console.log('%c  ', `background:url("${img}");padding:45px;background-size:100%; background-repeat:no-repeat;`)
    console.log(`%c METHOD 方法:`, 'color:#CC33CC', fname)
    // console.log(' ')
    console.log(`%c PARAMS 参数:`, 'color:#FF9933', params)
    if (data.err) {
      console.log(`%c RESULT ERROR 失败结果:`, 'color:#993333', data.err)
    } else {
      console.log(`%c RESULT DATA 成功结果:`, 'color:#99CC00', data.data)
    }
    console.log(`%c TIME 时间:`, 'color:#FF0066', Date.now() - start + 'ms')
    console.groupEnd()
    return data
  })
}
// 导出动画
function animationend () {
  const container = document.querySelector('body')
  const div = document.createElement('i')
  div.className = 'el-icon-document'
  div.style.fontSize = '50px'
  div.style.color = '#dd6161'
  div.style.position = 'fixed'
  div.style.right = `${container.offsetWidth / 2}px`
  div.style.top = `${container.offsetHeight / 2}px`
  div.style.animation = 'flyIn .7s'
  const handler = () => container.removeChild(div)
  div.addEventListener('webkitAnimationEnd', handler)
  div.addEventListener('animationEnd', handler)
  container.appendChild(div)
}
// 导出中间件
export const exportMiddleware = pageEntity => vue => next => (...params) => {
  const { page = 1, pageSize = 10 } = pageEntity
  // const hours = new Date().getHours()
  // if (!(hours >= 15 || hours < 8)) {
  //   vue.prototype.$message.error('导出功能暂时关闭，每日下午三点开放，敬请谅解')
  //   return Promise.resolve({ err: '导出功能暂时关闭，每日下午三点开放，敬请谅解' })
  // }
  return next(...params.map(item => {
    if (item && item.searchConditionParams) {
      return { ...item, pageIndex: page, pageSize: pageSize }
    }
    return item
  })).then(data => {
    if (!data.err) animationend()
    return data
  })
}
